<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片下载器</title>
    <!-- 添加网页图标 -->
    <link rel="icon" type="image/x-icon" href="/static/favicon.ico">
    <!-- 添加更多图标支持 -->
    <link rel="apple-touch-icon" sizes="180x180" href="/static/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/static/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/static/favicon-16x16.png">
    <!-- 引入 Element UI 的样式和 Vue -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <style>
        body {
            margin: 0;
            background-color: #f5f7fa;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
        }

        .app-container {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .header-card {
            margin-bottom: 20px;
        }

        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .image-item {
            position: relative;
            background: #fff;
            border-radius: 4px;
            overflow: hidden;
        }

        .image-item img {
            width: 100%;
            height: 200px;
            object-fit: cover;
            display: block;
        }

        .image-info {
            padding: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #fff;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .search-box {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .empty-text {
            text-align: center;
            color: #909399;
            padding: 40px 0;
        }
    </style>
</head>

<body>
    <div id="app" class="app-container">
        <el-card class="header-card">
            <div slot="header">
                <h2 style="margin: 0">网页图片下载器</h2>
            </div>
            
            <div class="search-box">
                <el-input
                    v-model="url"
                    placeholder="请输入网址"
                    style="margin-right: 10px;">
                </el-input>
                
                <el-select v-model="loadMethod" style="width: 200px; margin-right: 10px;">
                    <el-option
                        label="BeautifulSoup (静态加载)"
                        value="soup">
                    </el-option>
                    <el-option
                        label="Selenium (动态加载)"
                        value="selenium">
                    </el-option>
                </el-select>
                
                <el-button 
                    type="primary" 
                    @click="fetchImages"
                    :loading="loading">
                    {{ loading ? '正在分析...' : '搜索图片' }}
                </el-button>
                <el-button 
                    type="success" 
                    @click="downloadSelected" 
                    :loading="downloading"
                    :disabled="!selectedImages.length || downloading"
                    v-if="images.length">
                    {{ downloading ? '正在下载...' : `下载选中图片 (${selectedImages.length})` }}
                </el-button>
            </div>

            <div class="toolbar" v-if="images.length">
                <div>
                    <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
                </div>
                <el-select v-model="sizeFilter" placeholder="图片大小筛选" @change="handleSizeFilter">
                    <el-option label="所有尺寸" value="all"></el-option>
                    <el-option label="大图 (>500KB)" value="large"></el-option>
                    <el-option label="中等 (100KB-500KB)" value="medium"></el-option>
                    <el-option label="小图 (<100KB)" value="small"></el-option>
                </el-select>
            </div>
        </el-card>

        <el-card v-if="images.length" body-style="padding: 20px;">
            <div class="image-grid">
                <div v-for="(image, index) in filteredImages" :key="index" class="image-item">
                    <el-image 
                        :src="image.url" 
                        fit="cover"
                        :preview-src-list="[image.url]">
                    </el-image>
                    <div class="image-info">
                        <el-checkbox v-model="image.selected">选择</el-checkbox>
                        <!-- <span>{{ formatSize(image.size) }}</span> -->
                    </div>
                </div>
            </div>
        </el-card>

        <div v-if="!images.length && !loading" class="empty-text">
            <el-empty description="暂无图片数据"></el-empty>
        </div>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    url: '',
                    loadMethod: 'soup',  // 默认使用 soup
                    images: [],
                    loading: false,
                    downloading: false,
                    currentDomain: '',
                    selectAll: false,
                    sizeFilter: 'all',
                    pageTitle: ''
                }
            },
            computed: {
                selectedImages() {
                    return this.images.filter(img => img.selected);
                },
                filteredImages() {
                    return this.images.filter(img => {
                        switch(this.sizeFilter) {
                            case 'large':
                                return img.size > 500000;
                            case 'medium':
                                return img.size >= 100000 && img.size <= 500000;
                            case 'small':
                                return img.size < 100000;
                            default:
                                return true;
                        }
                    });
                }
            },
            methods: {
                async fetchImages() {
                    if (!this.url) {
                        this.$message.warning('请输入有效的网址');
                        return;
                    }

                    this.loading = true;
                    this.downloading = false;
                    try {
                        const response = await fetch('/fetch-images', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ 
                                url: this.url,
                                method: this.loadMethod
                            })
                        });
                        const data = await response.json();
                        
                        if (data.images && data.images.length > 0) {
                            this.currentDomain = data.domain;
                            this.pageTitle = data.title;
                            console.log('Page title:', data.title);
                            this.images = data.images.map(img => ({
                                ...img,
                                selected: true
                            }));
                            this.selectAll = true;
                            this.$message.success(`找到 ${data.images.length} 张图片`);
                        } else {
                            this.$message.warning('未找到任何图片');
                        }
                    } catch (error) {
                        this.$message.error('获取图片失败，请重试');
                    } finally {
                        this.loading = false;
                    }
                },
                async downloadSelected() {
                    const selectedUrls = this.selectedImages.map(img => img.url);
                    console.log('Downloading with title:', this.pageTitle);
                    
                    if (selectedUrls.length === 0) {
                        this.$message.warning('请选择要下载的图片');
                        return;
                    }

                    this.downloading = true;
                    try {
                        const response = await fetch('/download-selected', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                urls: selectedUrls,
                                domain: this.currentDomain,
                                title: this.pageTitle
                            })
                        });
                        const data = await response.json();
                        this.$message.success(data.message);
                    } catch (error) {
                        this.$message.error('下载失败，请重试');
                    } finally {
                        this.downloading = false;
                    }
                },
                handleSelectAll(val) {
                    this.images.forEach(img => img.selected = val);
                },
                handleSizeFilter() {
                    // 尺寸筛选时重置选择状态
                    this.selectAll = false;
                    this.images.forEach(img => img.selected = false);
                },
                formatSize(bytes) {
                    if (bytes === 0) return '0 B';
                    const k = 1024;
                    const sizes = ['B', 'KB', 'MB', 'GB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
                }
            }
        });
    </script>
</body>

</html>